package dmt16.TelemetrySuit.Controller.SensorTypes
{
	import dmt16.TelemetrySuit.Utils.Calculation;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	public class ForceSensor implements ISensorType
	{
		public function ForceSensor()
		{
		}
		
		public function get sensorType():int
		{
			return SensorType.FORCE_SENSOR;
		}
		
		public function get dataFormat():int
		{
			return DataFormat.UInt16;
		}
		
		public function get cadence():Number{
			return _cadence;
		}
		
		private var _data:Vector.<Number>=new Vector.<Number>();
		public function get data():Vector.<Number>{
			return _data;
		}
		
		private static const WINDOW_SIZE:Number=40;
		
		private var _lastPulseTime:Number=0;
		private var _lastMeasure:Number=0;
		private var _cadence:Number=0;
		
		private var _n:Number=0;
		private var _movingAverage:Vector.<Number>=new Vector.<Number>();
		public function get movingAverage():Vector.<Number>{
			return _movingAverage;
		}
		private var _xdata:Vector.<Number>=new Vector.<Number>();
		public function get xdata():Vector.<Number>{
			return _xdata;
		}		
		
		public function addData(value:*, time:Number):void
		{
			var val:Number=1023-(value as Number);
			_data.push(val);
			if(_data.length<=WINDOW_SIZE){
				_n+=val;
			}
			else{
				_n+=val-_data[_data.length-WINDOW_SIZE-1];
				_movingAverage.push(_n/WINDOW_SIZE);
				_xdata.push(_data.length-WINDOW_SIZE/2);
				if(val>(_n/WINDOW_SIZE)&&_lastMeasure<(_n/WINDOW_SIZE)){
					if(_lastPulseTime>0){
						var p:Number=60000/(time-_lastPulseTime);
						if(_cadence==0)
							_cadence=p;
						else
							_cadence=(p*2+_cadence)/3;
					}
					_lastPulseTime=time;
				}
			}
			_lastMeasure=val;
			_eventManager.dispatchEvent(new SensorEvent(SensorEvent.SENSOR_DATA_EVENT));
		}
		
		private var _eventManager:EventDispatcher=new EventDispatcher();
		public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
		{
			_eventManager.addEventListener(type,listener,useCapture,priority,useWeakReference);
		}
		public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void{
			_eventManager.removeEventListener(type,listener,useCapture);
		}
		public function dispatchEvent(event:Event):Boolean{
			return _eventManager.dispatchEvent(event);
		}
		public function hasEventListener(type:String):Boolean{
			return _eventManager.hasEventListener(type);
		}
		public function willTrigger(type:String):Boolean{
			return _eventManager.willTrigger(type);
		}
	}
}